from zope.interface import implements

from twisted.words.protocols import irc
from twisted.internet import protocol, reactor, defer
from twisted.plugin import IPlugin

from pyhnode import interfaces

class IRCProtocol(irc.IRCClient):

    def connectionMade(self):
        self.nickname = self.factory.nickname
        irc.IRCClient.connectionMade(self)

    def privmsg(self, user, channel, msg):
        user = user.split('!')[0]
        if self.nickname.lower() == channel.lower():
            d = self.factory.getAnswer(msg)
            d.addErrback(catchError)

            def writeValue(value):
                self.msg(channel, value)

            d.addCallback(writeValue)

class IRCFactoryFromService(protocol.ClientFactory):

    implements(IPlugin, interfaces.INetworkFactory)

    protocol = IRCProtocol
    nickname = None

    def __init__(self, service):
        sekf.service = service

    def getAnswer(self, msg):
        return self.service.getAnswer(msg)

class pluginConnector(object):

#    implements(IPlugin, interfaces.INetPlugin)

    def __init__(self):
        self.name = "irc"

    def getName(self):
        return self.name

    def makeService(self, parser, conf):
        """This part is tricky, i want to use client verification (the client's certificate has to
        bi signed by the server, but the twisted.internet.ssl.CertificateOptions doesn't work, and
        it isn't well documented. I had to use PrivateCertificate.options(), which makes what i
        need."""
        self.servers = conf.get(self.name, 'servers').split(',')
        self.nick = conf.get('general', 'nodename')
        components.registerAdapter(IRCFactoryFromService,
            interfaces.IParserService,
            interfaces.INetworkFactory)
        try:
            sslenabled = conf.get(self.name, 'ssl') == "true"
        except:
            sslenabled = False
        if sslenabled:
            self.port = conf.getint(self.name, 'sslport')
            certfile = conf.get(self.name, 'sslcert')
            cert = ssl.PrivateCertificate.loadPEM(open(certfile).read())
            ctx = cert.options(cert)
            s = internet.SSLClient(self.port, interfaces.INetworkFactory(parser), ctx)
        else:
            self.port = conf.getint(self.name, 'port')
            self.addr = conf.get(self.name, 'addr')
            s = internet.TCPClient(self.port, interfaces.INetworkFactory(parser))
        return s

#pc = pluginConnector()

